import getEchartLayer from './echartLayer.js';
let cLyr;
let chart;
let updateChart;

function processData(projList) {
  if (!projList.length) {
    return;
  }
  let geoCoordTabel = {
    ['无锡市城市重点建设项目管理中心']: [120.29945, 31.575001],
  };

  let fromToData = [
    // [{ name: '无锡市城市重点建设项目管理中心' }, { name: '上海', value: 95 }],
  ];

  projList.forEach(proj => {
    let projectName = proj.projectName.trim();
    let lng = proj.lng.trim();
    let lat = proj.lat.trim();
    geoCoordTabel[projectName] = [lng, lat];

    // 双向流动效果
    fromToData.push(
      [
        { name: '无锡市城市重点建设项目管理中心' },
        {
          name: projectName,
          // value: Math.ceil(Math.random() * 100),
          value: 100,
        },
      ],
      [
        { name: projectName },
        {
          name: '无锡市城市重点建设项目管理中心',
          // value: Math.ceil(Math.random() * 100),
          value: 100,
        },
      ],
    );
  });

  function convertData(list) {
    return list.reduce((r, e) => {
      let fromCoord = geoCoordTabel[e[0].name];
      let toCoord = geoCoordTabel[e[1].name];
      fromCoord &&
        toCoord &&
        r.push({
          fromName: e[0].name,
          toName: e[1].name,
          coords: [fromCoord, toCoord],
          value: e[1].value || 1,
        });
      return r;
    }, []);
  }

  return convertData(fromToData);
}

export function initEchartsLayer(projList) {
  const data = processData(projList);

  var option = {
    title: {
      show: false,
    },
    series: [
      {
        name: '数据传输示意',
        type: 'lines',
        coordinateSystem: 'arcgis',
        zlevel: 1,
        effect: {
          show: true,
          period: 6,
          trailLength: 0.8,
          color: '#fff',
          symbolSize: 3,
        },
        lineStyle: {
          normal: {
            // color: '#a6c84c',
            width: 0,
            // curveness: 0.2,
          },
        },
        data,
      },
    ],
  };
  // var chart = new echartsLayer(view, option);
  getEchartLayer().then(EchartsLayer => {
    cLyr = new EchartsLayer(window.agsGlobal.view, option);
    chart = cLyr.chart;
    updateChart = chart.setOption.bind(chart);
  });
}

export function updateEchartsLayer(projList) {
  console.log(projList);
  if (!chart) {
    console.warn('图层还未初始化');
  }
  const data = processData(projList);
  var option = {
    title: {
      show: false,
    },
    series: [
      {
        name: '数据传输示意',
        type: 'lines',
        coordinateSystem: 'arcgis',
        zlevel: 1,
        effect: {
          show: true,
          period: 6,
          trailLength: 0.8,
          color: '#fff',
          symbolSize: 3,
        },
        lineStyle: {
          normal: {
            // color: '#a6c84c',
            width: 0,
            // curveness: 0.2,
          },
        },
        data,
      },
    ],
  };

  console.log(option);
  cLyr.setChartOption(option);
  // updateChart(option);
}
